package com.appliance.cycling2011.rss;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.appliance.cycling2011.BrowserActivity;
import com.appliance.cycling2011.R;
import com.appliance.cycling2011.RootActivity;
import com.appliance.cycling2011.download.DownloadRssThread;
import com.appliance.cycling2011.download.DownloadThread;
import com.appliance.cycling2011.rsshandling.AndroidSaxFeedParser;
import com.appliance.cycling2011.rsshandling.Message;

public class RssActivity extends ListActivity {

	private List<Message> messages;
	protected final static String PATH_DIR = RootActivity.PATH_DIR;
	String rssFileName = RootActivity.rssUciNewsFilename;
	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle icicl) {
		super.onCreate(icicl);
		setContentView(R.layout.news);

		// Run class ProgressTask
		new ProgressTask(RssActivity.this).execute();
	}

	// Create menu-button
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(Menu.NONE, MenuItems.UPDATE_FEED.ordinal(), MenuItems.UPDATE_FEED.ordinal(), R.string.update_feed);
		return true;
	}

	// If menu-button is clicked, update news
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		super.onMenuItemSelected(featureId, item);
		switch (item.getItemId()) {
		case 0:
			return update(getApplicationContext());
		}
		return true;
	}

	public boolean update(Context con) {
		Intent myIntent = getIntent();
		String url = myIntent.getStringExtra("url");
		int nr = RootActivity.getRssNumber(url);

		Thread firstTime = new DownloadRssThread(con, url);
		firstTime.start();

		DownloadThread.getFinished().remove(nr);
		finish();
		startActivity(myIntent);

		return true;

	}

	// Handles a click on a specific news, and opens a new activity
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Intent intent = new Intent(RssActivity.this, BrowserActivity.class);
		intent.putExtra("url", messages.get(position).getLink().toString());
		this.startActivity(intent);
	}

	// progress dialog to show user that the background is processing.
	private class ProgressTask extends AsyncTask<String, Void, Boolean> {
		private ListActivity activity;
		private Context context;

		public ProgressTask(ListActivity activity) {
			this.activity = activity;
			context = activity;
			dialog = new ProgressDialog(context);
		}

		protected void onPreExecute() {

			String loading;

			loading = getResources().getString(R.string.loading);

			dialog.setMessage(loading);
			dialog.show();
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			try {

				// Create Hashmap and save title and description in the
				// ArrayList
				List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(messages.size());
				for (Message msg : messages) {
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("title", msg.getTitle());
					map.put("description", msg.getDescription());
					map.put("pubdate", msg.getDate().substring(5, 22));
					map.put("comment", Integer.toString(msg.getComment()));
					list.add(map);
				}

				// Tells the adapter which keys to get
				String[] from = { "title", "description", "pubdate" };
				int[] to = { R.id.title, R.id.description, R.id.pubdate };

				SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(), list, R.layout.row, from, to);

				activity.setListAdapter(adapter);

				if (dialog.isShowing()) {
					dialog.dismiss();
				}

			} catch (Exception e) {
				if (dialog.isShowing()) {
					dialog.dismiss();
					Toast.makeText(context, R.string.error_retrying, Toast.LENGTH_LONG).show();
					// update(context);
				}
			}
		}

		// Parse the URL while loading
		protected Boolean doInBackground(final String... args) {
			try {
				Intent myIntent = getIntent();
				String url = myIntent.getStringExtra("url");

				int nr = RootActivity.getRssNumber(url);
				String xml = PATH_DIR + rssFileName + nr + ".xml";

				AndroidSaxFeedParser parser;
				if (new File(xml).exists()) {
					parser = new AndroidSaxFeedParser(xml);
				} else {
					parser = new AndroidSaxFeedParser(url);
				}

				while (!DownloadThread.getFinished().contains(Integer.toString(nr)))
					;

				messages = parser.parse();

				return true;
			} catch (Exception e) {

				return false;
			}
		}
	}
}
